class ImportController < ApplicationController

  def select
    @user = current_user
    session[:ImportPosts] = "abc"
  end

  def list
    @user = current_user
    @user.del_account = params[:user][:del_account]
    @user.del_password = params[:user][:del_password]
    @user.save if params[:remember] == "1"
    @posts = get_from_del(@user.del_account, @user.del_password, params[:del_scope], params[:del_tag])
    @last_update = get_last_update(@user.del_account, @user.del_password)

    session[:ImportPosts] = @posts
  end

  def create
    @msg=""
    @posts = session[:ImportPosts]  #get_from_del("bbpnb", "nb0275", "recent", "")
    #@posts = @posts[4..6]
    @posts.each do |p|
      source = Source.find_by_uri(p.url.to_s)
      if source.nil?
        source = Source.new(:uri=>p.url.to_s, :first_poster=>current_user.login)
        source.save
      end


      if Bookmark.find_by_user_id_and_source_id(current_user.id, source.id).nil?
        bookmark= Bookmark.new(:source_id=>source.id, :user_id=>current_user.id)
        bookmark.title = p.title
        bookmark.note = p.notes
        bookmark.from = "delicious"
        bookmark.created_at = p.time
        bookmark.tag_list = p.tags.map{|t| t.to_s}.join(",")
          if bookmark.save
             @msg += bookmark.title + " save ok<br/>"
          else
             @msg += bookmark.title + " save error<br/>"
          end
        end

      end
      session[:ImportPosts] = nil
    
  end



  private
  def get_from_del(account, password, scope, tag)
    d = WWW::Delicious.new(account, password)

      case scope
        when "recent"
          d.posts_recent()
        when "all"
          d.posts_all()
        when "tagged"
          d.posts_all(:tag=>tag)
      end
  end

  def get_last_update(account, password)
    d = WWW::Delicious.new(account, password)
    d.update
  end
end
